const { Teacher, User, Class } = require('../models/db');

const ok = (res, data, extra = {}) => res.json({ success: true, data, ...extra });
const fail = (res, code = 500, message = '服务器错误') => res.status(code).json({ success: false, message, code });

const mapTeacherToClient = (t) => {
  // 确定职位：根据是否有班级和状态
  let position = '教师';
  if (t.classes && Array.isArray(t.classes) && t.classes.length > 0) {
    position = '讲师';
  }
  // 检查是否是导员（通常导员会作为advisor关联到班级）
  // 这里可以通过检查user role或者classes来判断
  
  return {
    id: t._id?.toString(),
    teacherId: t.teacherId,
    name: t.name,
    gender: t.gender,
    academy: t.academy,
    phone: t.phone,
    email: (t.user && t.user.email) ? t.user.email : undefined,
    position: position,
    status: t.status || '在职',
    classes: (t.classes && Array.isArray(t.classes)) ? t.classes.map(c => ({
      id: c._id?.toString(),
      className: c.className || c.name
    })) : [],
    userId: t.user ? t.user._id?.toString() : undefined,
    createdAt: t.createdAt ? new Date(t.createdAt).toISOString() : undefined,
    updatedAt: t.updatedAt ? new Date(t.updatedAt).toISOString() : undefined,
  };
};

const mapClientToTeacher = (body) => ({
  teacherId: body.teacherId,
  name: body.name,
  gender: body.gender,
  academy: body.academy,
  phone: body.phone,
  status: body.status,
  classes: body.classes || [],
  user: body.userId,
  updatedAt: new Date(),
});

exports.getAllTeachers = async (req, res) => {
  try {
    const { page = 1, limit = 20, academy, status } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);
    const query = {};
    
    if (academy) query.academy = academy;
    if (status) query.status = status;
    
    const teachers = await Teacher.find(query)
      .populate('classes', 'className academy stage')
      .populate('user', 'username email role')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    const total = await Teacher.countDocuments(query);
    ok(res, teachers.map(mapTeacherToClient), {
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        totalPages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.getTeacherById = async (req, res) => {
  try {
    const t = await Teacher.findById(req.params.id)
      .populate('classes', 'className academy stage')
      .populate('user', 'username email role');
    if (!t) return fail(res, 404, '未找到该教师');
    ok(res, mapTeacherToClient(t));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.createTeacher = async (req, res) => {
  try {
    const payload = mapClientToTeacher(req.body || {});
    if (!payload.teacherId || !payload.name || !payload.gender || !payload.academy || !payload.phone) {
      return fail(res, 400, '缺少必要字段: teacherId | name | gender | academy | phone');
    }
    
    const exist = await Teacher.findOne({ teacherId: payload.teacherId });
    if (exist) return fail(res, 400, '学工号已存在');
    
    const created = await Teacher.create(payload);
    const t = await Teacher.findById(created._id)
      .populate('classes', 'className')
      .populate('user', 'username');
    ok(res, mapTeacherToClient(t));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.updateTeacher = async (req, res) => {
  try {
    const payload = mapClientToTeacher(req.body || {});
    payload.updatedAt = new Date();
    const updated = await Teacher.findByIdAndUpdate(req.params.id, payload, { new: true })
      .populate('classes', 'className')
      .populate('user', 'username');
    if (!updated) return fail(res, 404, '未找到该教师');
    ok(res, mapTeacherToClient(updated));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.deleteTeacher = async (req, res) => {
  try {
    const deleted = await Teacher.findByIdAndDelete(req.params.id);
    if (!deleted) return fail(res, 404, '未找到该教师');
    ok(res, { id: req.params.id });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

